/* eslint-disable no-param-reassign */

import { message } from 'antd';
import router from 'umi/router';
import {
  getTypeList,
  getAreaList,
  getList,
  delList,
  getMatListPage,
  getMatList,
  getJudgeDict,
  getMatDetail,
  getDict,
  save,
  update,
} from '@/services/inservicematerial';
import changeName from '../InserviceMaterial/changeTxt';

export default {
  state: {
    data: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
    },
    areaList: [],
    formFieldsValue: {},
    expandForm: false,
    matList: [],
    // 新增
    coltFlag: '1',
    titleArr: [true],
    headertitle: ['标题'],
    tValue: [[]],
    newNo: 0,
    tableArr: [{ pageIdEdit: 0, maGpDetails: [] }],
    requestData: [],
    addMetial: [],
    tableJudge: [],
    logicList: [],
    tValues: '1',
    index: 0,
    bigResult: [],
  },

  effects: {
    // 获取服务类型
    *fetchSerTypeList({ payload }, { call, put }) {
      const response = yield call(getTypeList, payload);
      if (response.success) {
        yield put({
          type: 'getTypeList',
          payload: response.data,
        });
      } else {
        yield put({
          type: 'getTypeList',
          payload: [],
        });
        message.warning(`${response.message || '查询失败！'}`);
      }
      return response;
    },
    // 获取地区
    *fetchAreaList({ payload }, { call, put }) {
      const response = yield call(getAreaList, payload);
      if (response.success) {
        yield put({
          type: 'getAreaList',
          payload: response.data,
        });
      }
    },
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getList, payload);
      const {
        page: { currentPage, pageSizes },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize: pageSizes,
          },
        });
      } else {
        message.error(response.message);
      }
    },
    // 列表删除
    *fetchDelete({ payload }, { call, put, select }) {
      const response = yield call(delList, payload);
      if (response.success) {
        message.success('删除成功！');
        let values;
        yield select(state => {
          const currentPage = state.inservicematerial.data.pagination.current;
          const { pageSize } = state.inservicematerial.data.pagination;
          const { formFieldsValue } = state.inservicematerial;
          const page = { currentPage, pageSizes: pageSize };
          values = {
            page,
            mat: { ...formFieldsValue },
          };
        });
        yield put({
          type: 'fetchList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '删除失败！'}`);
      }
    },
    // 获取材料
    *fetchMatListPage({ payload }, { call, put }) {
      const response = yield call(getMatListPage, payload);
      if (response.success) {
        yield put({
          type: 'getMatListPage',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    },
    // 获取材料
    fetchMatList:[
      function *({ payload }, { call, put }) {
      const response = yield call(getMatList, payload);
      if (response.success) {
        yield put({
          type: 'getMatList',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    }, { type:'throttle' ,ms: 1000 }],
    // 获取材料判断下拉
    *fetchJudgeDict({ payload }, { call, put }) {
      const response = yield call(getJudgeDict, payload);
      if (response.success) {
        yield put({
          type: 'getJudgeDict',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    },
    // 获取字典
    *fetchDict({ payload }, { call, put, select }) {
      const response = yield call(getDict, payload);
      const matPkgId = yield select(state => state.routing.location.query.id);
      if (response.success) {
        yield put({
          type: 'getDict',
          payload: response.data,
        });
        // 地区
        const resArea = yield call(getAreaList, {});
        if (resArea.success) {
          yield put({
            type: 'getAreaList',
            payload: resArea.data,
          });
        } else {
          message.warning(resArea.message);
        }
        // 详情
        if (matPkgId) {
          const res = yield call(getMatDetail, { matPkgId });
          if (res.success) {
            yield put({
              type: 'getMatDetail',
              payload: res.data,
            });
          } else {
            message.warning(res.message);
          }
        }
      } else {
        message.warning(response.message);
      }
    },
    // 保存
    *fetchSave({ payload }, { call, select }) {
      const { matPkgId, serTypeId, serType, vno } = yield select(state => state.inservicematerial);

      const response = matPkgId
        ? yield call(update, { ...payload, matPkgId, vno, serType, serTypeId })
        : yield call(save, payload);
      if (response.success) {
        if (response.data) {
          message.warning('温馨提示：您配置的地区与材料类型已存在');
        } else {
          router.goBack();
        }
      } else {
        message.warning(response.message);
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 获取字典
    getDict(state, { payload }) {
      return {
        ...state,
        flagList: payload.YES_NO_FLAG,
        inputType: payload.INPUT_TYPE,
        contractlist: payload.SER_TYPE, // 合同类型
      };
    },
    // 材料展示
    getMatListPage(state, { payload }) {
      return {
        ...state,
        requestData: payload.pageRecords,
        addMetial: JSON.parse(JSON.stringify(payload.pageRecords)),
        tableJudge: JSON.parse(JSON.stringify(payload.pageRecords)),
        cmTotal: payload.totalCount,
      };
    },
    // 获取材料
    getMatList(state, { payload }) {
      return {
        ...state,
        bigResult: payload,
      };
    },
    // 获取材料判断
    getJudgeDict(state, { payload }) {
      return {
        ...state,
        logicList: payload,
      };
    },

    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取地区
    getAreaList(state, { payload }) {
      return {
        ...state,
        areaList: payload,
      };
    },
    // 获取类型
    getTypeList(state, { payload }) {
      return {
        ...state,
        matList: payload,
      };
    },
    // 增talbe
    addTable(state) {
      const newState = state;
      newState.tableArr.push({ pageIdEdit: (newState.index += 1), maGpDetails: [] });
      newState.titleArr.push(true);
      newState.headertitle.push('标题');
      newState.tValue.push([]);
      return {
        ...state,
      };
    },
    // 修改titile
    modifyTitle(state, { payload }) {
      state.titleArr.splice(payload, 1, false);
      return {
        ...state,
      };
    },
    //  保存title
    saveTitle(state, { payload }) {
      state.titleArr.splice(payload, 1, true);
      return {
        ...state,
      };
    },
    // 改变title
    changeTitle(state, { payload }) {
      state.headertitle.splice(payload.i, 1, payload.v);
      return {
        ...state,
      };
    },
    // 修改表格
    updateTable(state, { payload }) {
      const newPayload = payload;
      state.tableArr[state.newNo].maGpDetails.push(newPayload);
      state.tValue[state.newNo].push([]);
      if (Number(newPayload.judgeFlag) === 1) {
        newPayload.children = [];
      }
      return {
        ...state,
      };
    },
    // 修改表格children
    updateTableChild(state, { payload }) {
      const newPayload = payload;
      newPayload.selectedRows.judgeLogicName = state.tValues;
      newPayload.selectedRows.judgeLogicCode = state.tValueCode;
      state.tableArr[state.newNo].maGpDetails[state.newButton].children.push(
        newPayload.selectedRows
      );
      state.tValue[state.newNo][state.newButton].push(newPayload.obj);

      return {
        ...state,
      };
    },
    // 删除页
    deletePage(state, { payload }) {
      if (state.tableArr[state.newNo].maGpDetails) {
        state.tableArr[state.newNo].maGpDetails.forEach(item => {
          const newItem = item;
          state.requestData.forEach(c => {
            if (newItem.matId === c.matId) {
              delete newItem.judgeLogicName;
              delete newItem.judgeLogicCode;
            }
          });
          if (newItem.children) {
            newItem.children.forEach(d => {
              state.requestData.forEach(c => {
                if (c.matId === d.matId) {
                  delete newItem.judgeLogicName;
                  delete newItem.judgeLogicCode;
                }
              });
            });
            delete newItem.children;
          }
        });
      }
      const newTableArr = state.tableArr.filter(item => item.pageIdEdit !== payload.pageIdEdit);
      state.tValue.splice(payload.i, 1);
      state.headertitle.splice(payload.i, 1);
      return {
        ...state,
        tableArr: newTableArr,
      };
    },
    // 删除行
    deletePageDom(state, { payload }) {
      const newRecord = payload.record;
      if (state.tableArr[state.newNo].maGpDetails[payload.i].children) {
        state.tableArr[state.newNo].maGpDetails[payload.i].children.forEach(c => {
          state.requestData.forEach(item => {
            const newItem = item;
            if (c.matId === item.matId) {
              delete newItem.judgeLogicName;
              delete newItem.judgeLogicCode;
            }
          });
        });
        delete newRecord.children;
      }
      const newTableArr = state.tableArr[state.newNo].maGpDetails.filter(
        item => item.matId !== payload.record.matId
      );
      state.tableArr[state.newNo].maGpDetails = newTableArr;
      return {
        ...state,
        ...payload,
      };
    },
    // 删除子
    deletePageChildDom(state, { payload }) {
      state.tableArr[state.newNo].maGpDetails.forEach(c => {
        const newC = c;
        if (newC.children) {
          newC.children.forEach(k => {
            if (k.matId === payload.record.matId) {
              state.requestData.forEach(item => {
                const newItem = item;
                if (payload.record.matId === newItem.matId) {
                  delete newItem.judgeLogicName;
                  delete newItem.judgeLogicCode;
                  let a;
                  state.tValue[state.newNo].forEach((itemV, y) => {
                    const newItemV = itemV;
                    if (newItemV) {
                      a = newItemV.filter(newItems => newItems.matId !== payload.record.matId);
                    }
                    state.tValue[state.newNo][y] = a;
                  });
                }
              });
              const tableArrChild = newC.children.filter(
                item => item.matId !== payload.record.matId
              );
              newC.children = tableArrChild;
            }
          });
        }
      });
      return {
        ...state,
        ...payload,
      };
    },
    // 获取详情数据
    getMatDetail(state, { payload }) {
      const headertitle = [];
      const titleArr = [];
      const tValue = [];
      const newPayload = payload;
      Object.keys(payload).forEach(key => {
        if (key === 'areaId' || key === 'areaName') {
          const a1 = payload.areaId.split(',');
          const b1 = payload.areaIdName.split(',');
          const areaIdArr = [];
          for (let i = 0; i < a1.length; i += 1) {
            areaIdArr.push({ key: a1[i], label: b1[i] });
          }
          newPayload.areaIds = areaIdArr;
        } else if (
          key === 'remark' ||
          key === 'serTypeIdName' ||
          key === 'serTypeName' ||
          key === 'coltFlag'
        ) {
          newPayload[key] = payload[key].toString();
        }
        if (state.inputType && state.flagList) {
          if (key === 'maGpages') {
            payload[key].forEach((item, i) => {
              payload[key][i].maGpDetails = changeName(
                item.maGpDetails,
                state.inputType,
                state.flagList
              );
              tValue.push([]);
              payload[key][i].maGpDetails.forEach((page, index) => {
                page[`check+${page.matId}`] = page.reqFlag === 1;
                tValue[i].push([]);
                if (page.children) {
                  page.children.forEach(padDetail => {
                    const obj = {};
                    obj.judgeLogicName = padDetail.judgeLogicName;
                    obj.judgeLogicCode = padDetail.judgeLogicCode;
                    obj.matId = padDetail.matId;
                    padDetail[`check+${padDetail.matId}`] = padDetail.reqFlag === 1;
                    tValue[i][index].push(obj);
                  });
                }
                if (!page.children && Number(page.judgeFlag) === 1) {
                  page.children = [];
                }
              });
              headertitle.push(item.pageName);
              titleArr.push(true);
              item.pageIdEdit = item.pageId;
            });
          }
        }
      });
      return {
        ...state,
        ...payload,
        headertitle,
        titleArr,
        tValue,
        tableArr: payload.maGpages,
      };
    },
  },
};
